/* eslint-disable */
import React, { Component } from 'react';
import ReactDom from 'react-dom';
import { Button, Tooltip } from 'antd';
import CockpitContainer from '../../../components/cockpit/CockpitContainer';
import GDMap from '../../../components/map/GDMap';
import styles from './index.less';
import LeftContent from './LeftContent';
import RightContent from './RightContent';
import { Marker } from "react-amap";
import CockpitBox from "../../../components/cockpit/CockpitBox";
// import ChartMove from './Charts/ChartMove';
import {
  qnhbMarkers,zsMarkers,qyMarkers,welMarkers
} from './config';
import CockpitMenuButtonSmall from '../../../components/cockpit/CockpitMenuButtonSmall';
import MyIcon from '../../../components/common/MyIcon';
import SlideBlock from '../../../components/common/SlideBlock';
import CockpitModal from '../../../components/cockpit/CockpitModal';
import Animation from '../../../components/common/Animation';

const ButtonGroup = Button.Group;
var disProvince, heatmap;
var adCode = 130000;
var depth = 2;
class ProcessSupervision extends Component {
  state = {
    leftSliderMode: "", // 左侧滑块动画模式  open(打开)、close(关闭)、closeToOpen(先关闭再打开)
    rightSliderMode: "", // 右侧滑块动画模式
    typeBtnKey: 1,

    isShowqnhb:true,
    isShowzs:true,
    isShowqy:true,
    isShowwel:true,

    
    moveMap: null,

    activeMapTypeIndex: 1,
    timeValueIndex: 0,
    projectHeatMapData : [],      // 项目个数热力图数据  二维数据 存放每个月的数据
    heatMapColor: ["#45B52B", "#87DE55", "#FFFF53", "#E8A759", "#FF0000"],
    heatMapRate: [0.2, 0.4, 0.6, 0.8, 1],
    maxHeatMapCount: 100,
  }

  // menuButtonList = menuButtons.apply(this);
  map = null;          // 高德地图实例
  polygons = [];
  markers = [];

  timer = null;
  timer2 = null;
  delay = 3000;        // 时间轴切换延时
  maxDelay = 6000;     // 时间轴未有任何操作的时间间隔

  toggleMarker = null;  // 地图添加或者删除marker
  toggle3Dlayer = null; // 地图显隐3Dlayer

  componentDidMount() {
    for(let i = 0; i < 12; i++) {

    }
    this.setState({})
  }

  componentWillUnmount() {
    this.stopPollTime();
  }

  stopPollTime = () => {
    clearTimeout(this.timer);
    clearTimeout(this.timer2);
  }

  pollTime = () => {
    const { timeValueIndex, activeMapTypeIndex } = this.state;
    this.stopPollTime();
    this.timer = setTimeout(() => {
      this.setState({
        timeValueIndex: timeValueIndex >= 11 ? 0 : timeValueIndex + 1
      }, () => {
        if(activeMapTypeIndex === 0) {
          heatmap.hide();
          this.setState({
            isShowShaoxingshi: true
          })
        }else {
          heatmap.show();
          this.setHeatMapData()
        }
        this.pollTime();
      })
    }, this.delay)
  }

  clearMarkers = () => {
    this.map && this.map.remove(this.markers);
  }

  // 获取热力图数量区间 [100, 200, 300, 500, 1000]
  getHeatChartInterval = () => {
    // 向上取整 233333 -> 300000
    const getInteger = (count) => {
      if(!count) return 0;
      let integer = String(count).split('').map((m, i) => i === 0 ? +m + 1 : 0)
      return +integer.join('');
    }

    return this.state.heatMapRate.map((m, i) => {
      let count = (this.state.maxHeatMapCount * m || 0).toFixed(0);
      return getInteger(count) || 0
    })
  }

  // 热力图图例
  getHeatMapLengend = () => {
    if(this.state.activeMapTypeIndex !== 1) return;

    let interval = this.getHeatChartInterval();
    interval.unshift(interval[0])

    return (
      <Animation className="bounceInRight">
        <ul className={ styles["heat-map-lengend"] }>
          {
            this.state.heatMapColor.map((m, i) => (
              <li key={i}>
                <div className={styles["round"]} style={{ background : m }}></div>
                { (i === 0 ? "<" : "≥") + interval[i] }
              </li>
            ))
          }
        </ul>
      </Animation>
    )
  }

  // 高德地图加载完成事件
  handleMapCreated = (map, handle) => {
    this.map = map;
    this.toggleMarker = handle.toggleMarker;
    this.toggle3Dlayer = handle.toggle3Dlayer;
    this.onheatmap()
    this.setState({
      moveMap: map
    })
  }

  // 迁徙图创建完成回调
  handleMoveMapCreate = (map) => {
    this.state.moveMap = map;
    this.state.moveMap.on("click", this.mapClick)
    // this.createBorder();
  }



  hideMoveAll = () => {
    this.markers && this.state.moveMap.remove(this.markers)
    this.polygons && this.state.moveMap.remove(this.polygons)
  };

  getDomInnerHTML = (wrapperId, id, dom) => {
    let div = document.createElement("div");
    div.id = wrapperId;
    div.style.display = 'none';

    if(document.getElementById(wrapperId)) {
      document.getElementById(wrapperId).remove();
    }
    document.body.append(div);

    ReactDom.render(
      <div id={id}>{dom}</div>,
      document.getElementById(wrapperId)
    );

    return document.getElementById(id).innerHTML
  }



  // 设置地图中心点和缩放比例
  setZoomAndCenter = () => {
    this.map && this.map.setZoomAndCenter(10, [120.633541, 29.803041]);
  }

  // 标注图标
  getMarkerImg = (type,text, choose, i, m, isArea) => {

    const { shape, bgColor, color, value, style } = m;

    if(isArea) {
      return (
        <div className={styles["marker-zhishu"]} style={style}>
          <div>{value}</div>
        </div>
      )
    }



    return (
      <div className={!choose ? styles["marker-img-wrapper"] : styles["marker-img-choose"]}>
       <span style={{color:'#fff',fontSize:10}}>{text}</span>

      </div>
    )
  }

  // 地图标注点位
  getMarkers = (position, icon,text, i, handleClick) => {

    let markerEvents = {
      click: (MapsOption, marker) => {
        this.chooseLng = position.longitude;
        this.choosePos = position;
        handleClick && handleClick(MapsOption, marker);
      },
    }
    const choose = this.chooseLng == position.longitude;
    return (
      <Marker
        key={i}
        position={position}
        events={markerEvents}
      >
        {this.getMarkerImg(icon,text, choose, i, position)}
      </Marker>
    )
  }

  // 滑块切换事件
  handleSwitchChange = (type) => {
    if(type === 'shaoxingNum'){
      this.map.setZoomAndCenter(12, [120.382238, 29.692461]);
      this.setState({
        isShowShaoxingshiNum:false,
        isShowShaoxingshi:true
      })
      return
    }

    this.setState({
      isShowDevote: false,
      isShowXiBaoDevote: false,
      isShowXibaoMoFanDevote: false
    })

    if(type === 'yuanQu') {
      this.setState({
        isShowDevote: true
      })
    }

    if(type === 'xibao') {
      this.setState({
        isShowXiBaoDevote: true
      })
    }

    if(type === 'xibaoMoFan') {
      this.setState({
        isShowXibaoMoFanDevote: true
      })
    }

    this.setState({
      leftSliderMode: "",
      rightSliderMode: "",
      sliderContentType: type,
    }, () => {
      this.setState({
        leftSliderMode: "closeToOpen",
        rightSliderMode: "closeToOpen"
      });
    });
  };

  // 地图点击事件
  mapClick = (e) => {
    // console.log(`{ longitude: ${e.lnglat.getLng()}, latitude: ${e.lnglat.getLat()} },`);
    if (this.state.sliderContentType !== 'default' && this.state.sliderContentType != undefined) {
      this.chooseLng = '';
      this.setState({
        leftSliderMode: 'close',
        rightSliderMode: 'close',
        isShowDevote: false,
        isShowXiBaoDevote: false,
        isShowXibaoMoFanDevote: false,
      }, () => {
        setTimeout(() => {
          this.setState({
            sliderContentType: undefined,
            leftSliderMode: 'closeToOpen',
            rightSliderMode: 'closeToOpen',
          })
        }, 500)
      })
    }
    this.setZoomAndCenter();
  };
  //点击右侧细胞对标城市点位
  onRightChartBar = (name) => {
    let s = this.state;
    const map = this.map;
    if (name == '新昌县') {
      this.setState({
        isShowxinchangxian: !s.isShowxinchangxian
      }, () => {
        if (!s.isShowxinchangxian) {
          //this.initPro(330624, 2)
          map.setZoomAndCenter(10, [120.903866, 29.499832]);
        } else {
          disProvince && disProvince.setMap(null);
        }
      })
    } else if (name == '诸暨市') {
      this.setState({
        isShowgeJiShi: !s.isShowgeJiShi
      }, () => {
        if (!s.isShowgeJiShi) {
          map.setZoomAndCenter(10, [120.246863, 29.708692]);
          //this.initPro(330681, 2)
        } else {
          disProvince && disProvince.setMap(null);
        }
      })
    } else if (name == '嵊州市') {
      this.setState({
        isShowChengZhouShi: !s.isShowChengZhouShi
      }, () => {
        if (!s.isShowChengZhouShi) {
          map.setZoomAndCenter(10, [120.831025, 29.56141]);
          //this.initPro(330683, 2)
        } else {
          disProvince && disProvince.setMap(null);
        }
      })
    } else if (name == '上虞区') {
      this.setState({
        isShowShangYuQu: !s.isShowShangYuQu
      }, () => {
        if (!s.isShowShangYuQu) {
          map.setZoomAndCenter(10, [120.868122, 30.033121]);
          ////this.initPro(330604, 2)
        } else {
          disProvince && disProvince.setMap(null);
        }
      })
    } else if (name == '越城区') {
      this.setState({
        isShowyueChengQu: !s.isShowyueChengQu
      }, () => {
        if (!s.isShowyueChengQu) {
          map.setZoomAndCenter(10, [120.582633, 29.988245]);
          ////this.initPro(330602, 2)
        } else {
          disProvince && disProvince.setMap(null);
        }
      })
    } else if (name == '柯桥区') {
      this.setState({
        isShowkeQiaoQu: !s.isShowkeQiaoQu
      }, () => {
        if (!s.isShowkeQiaoQu) {
          map.setZoomAndCenter(10, [120.495065, 30.081942]);
          ////this.initPro(330603, 2)
        } else {
          disProvince && disProvince.setMap(null);
        }
      })
    }
  }

  initPro = (code, dep) => {

  }

  // 高德地图
  getMap = () => {
    let s = this.state;
    let markers = [


      { flag: s.isShowqnhb, list: qnhbMarkers, handleClick: () => this.handleSwitchChange('qnhb') },
      { flag: s.isShowzs, list: zsMarkers, handleClick: () => this.handleSwitchChange('zs') },
      { flag: s.isShowqy, list: qyMarkers, handleClick: () => this.handleSwitchChange('qy') },
      { flag: s.isShowwel, list: welMarkers, handleClick: () => this.handleSwitchChange('shequ') },

    ]

    return (
      <GDMap
        onClick={this.mapClick}
        onCreated={this.handleMapCreated}
      >
        {
          markers.map((item, index) => {
            if (item.flag) {
              return item.list.position.map((m, i) => this.getMarkers(m, item.list.icon,item.list.text, i, item.handleClick))
            }
          })
        }
      </GDMap>
    )
  }

  // 地图点位菜单按钮
  getMenuButton = () => {
    if(!this.state.onLeftChartBarflag) return

    let { typeBtnKey } = this.state;
    let wW = window.document.documentElement.clientWidth;
    let originLeft = (wW - this.menuButtonList.length * 250) / 2;
    return (
      <div className={styles["menu-button"]}>
        {this.menuButtonList.map((m, i) => {

          return (
            <CockpitMenuButtonSmall
              className="process-supervision-menu-button"
              text={m.text}
              style={{
                position: "absolute",
                bottom: 50,
                left: '50%',
                transform: 'translate(-50%)',
                zIndex: 999,
                // width:'50px'
              }}
              list={m.list}
            />
          )

        })}
      </div>
    );
  };

  typeBtnClick = (key) => {
    this.setState({
      typeBtnKey: key,
    }, () => {
      this.handleSwitchChange();
    })
  }



  //左侧图表事件
  onLeftCenter4 = () => {
    // console.log('onLeftCenter4')
    const map = this.map
    const s = this.state
    this.setState({
      isShowShaoxingshi: !s.isShowShaoxingshi,
      isShowMoreNums: false
    }, () => {
      if (!s.isShowShaoxingshi) {
        this.setZoomAndCenter()
        ////this.initPro(330600, 2)
      } else {
        disProvince && disProvince.setMap(null);
      }
    })

  }

  onLeftCenter5 = () => {
    // console.log('onLeftCenter5')
    const map = this.map
    const s = this.state
    this.setState({
      isShowShaoxingshiNum: !s.isShowShaoxingshiNum,
      isShowMoreNums: false
    }, () => {
      if (!s.isShowShaoxingshiNum) {
        this.setZoomAndCenter()
        this.setState({
          isShowShaoxingshi: false,
        })
        ////this.initPro(330600, 2)
      } else {
        disProvince && disProvince.setMap(null);
      }
    })
  }




  onheatmap = () => {
    const map = this.map;
    const { heatMapColor } = this.state;


  }






  // 时间刻度轴
  getTimeValue = () => {
    const { timeValueIndex, activeMapTypeIndex } = this.state;
    let getMonth = () => {
      return Array.from({ length: 11 }).map((m, i) => i + 2 + "月");
    }

    let data = ["2020", ...getMonth(), "2021"];

    const onClick = (m, i) => {
      if(i >= 12) return;
      this.setState({
        timeValueIndex: i
      }, () => {
        if(activeMapTypeIndex === 0) {
          this.setState({
            isShowShaoxingshi: true
          })
        }else {
          this.setHeatMapData()
        }
        this.stopPollTime();
        this.timer2 = setTimeout(() => {
          this.pollTime();
        }, this.maxDelay)
      })
    }

    return (
      <Animation className={"bounceInLeft"}>
        <div className={styles["time-value-wrapper"]}>
          <ul>
            {
              data.map((m, i) => (
                <Tooltip key={i} title={m}>
                  <li
                    className={(m.includes("月") ? "" : styles["year"]) + ' ' + (timeValueIndex === i ? styles["active"] : "")}
                    onClick={() => onClick(m, i)}
                  >
                    { m.includes("月") ? "" : m }
                  </li>
                </Tooltip>
              ))
            }
          </ul>
        </div>
      </Animation>
    )
  }

  handleYuanSuClick = (i) => {
    this.setState({
      activeMapTypeIndex: i
    }, () => {
      if(i === 0) {
        heatmap.hide()
        this.toggle3Dlayer(true);
        this.toggleMarker(true);
        this.setState({
          isShowShaoxingshi: true
        })
        this.stopPollTime();
        this.pollTime();
      }
      if(i === 1) {
        heatmap.show();
        this.toggle3Dlayer(false);
        this.setState({
          isShowShaoxingshi: false
        })
        this.stopPollTime();
        this.pollTime();
      }
    });
  }

  getYuanSuBtn = () => {
    const { activeMapTypeIndex } = this.state;

    return (
      <Animation className="jackInTheBox">
        <div className={styles["menu-Btn"]}>
          <span style={{ color: activeMapTypeIndex === 0 ? '#6FD0F3' : '#ccc', cursor: 'pointer' }} onClick={() => this.handleYuanSuClick(0)}>元素图</span>
          <span className={styles["zuoheng"]}></span>
          <span style={{ color: activeMapTypeIndex === 1 ? '#6FD0F3' : '#ccc', cursor: 'pointer' }} onClick={() => this.handleYuanSuClick(1)}>热力图</span>
        </div>
      </Animation>
    )
  }

  getHeatMapAbout = () => {
    if(this.state.onLeftChartBarflag) return
    return (
      <div className={styles["menu-button"]}>
        {/* { this.getYuanSuBtn() } */}
        { this.getHeatMapLengend() }
        { this.getTimeValue() }
      </div>
    )
  }

  // 获取当前的热力图数据
  getCurrentHeatMapData = () => {
    const { timeValueIndex, projectHeatMapData } = this.state;
    let project = projectHeatMapData[timeValueIndex] || [];
    return project
  }

  // 设置热力图数据
  setHeatMapData = () => {
    const data = this.getCurrentHeatMapData();
    heatmap && heatmap.setDataSet({
      data: data,
      max: 100
    });
  }

  // 左侧滑块
  getLeftSlider = () => {
    let { typeBtnKey, leftSliderMode, sliderContentType } = this.state;
    let width = document.body.clientWidth;
    let tableWidth = 400;
    if (width < 1367) {
        tableWidth = 350;
    }
    return (
      <SlideBlock
        mode={leftSliderMode}
        style={{
          position: "absolute",
          zIndex: 999,
          top: "10%",
          left:10,
          width: tableWidth
        }}
      >
        <div>
          <LeftContent
            data={this.choosePos}
            type={typeBtnKey}
            pointType={sliderContentType}
          />

        </div>
      </SlideBlock>
    );
  };

  // 右侧滑块
  getrightSlider = () => {
    let { typeBtnKey, rightSliderMode, sliderContentType } = this.state;
    let width = document.body.clientWidth;
    let tableWidth = 400;
    if (width < 1367) {
        tableWidth = 350;
    }
    return (
      <SlideBlock
        outClassName="fadeOutRight"
        inClassName="fadeInRight"
        mode={rightSliderMode}
        style={{
          position: "absolute",
          zIndex: 999,
          top: "10%",
          right: 10,
          width: tableWidth
        }}
      >
        <div>
          <RightContent type={typeBtnKey} pointType={sliderContentType} getImgInfo={this.getImgInfo} onRightChartBar={this.onRightChartBar} getImgInfoLct={this.getImgInfoLct}/>
        </div>
      </SlideBlock>
    );
  };

  getImgInfo = () => {
    this.setState({
      bigImgSrc: require("../../../assets/humian.jpg"),
      isShowBigImgModal: true
    })
  }

  getImgInfoLct = () => {
    this.setState({
      bigImgSrc: require("../../../assets/lct.png"),
      isShowBigImgModal: true
    })
  }

  // 图片预览弹窗
  getBigImgModal = () => {
    if (!this.state.isShowBigImgModal) return
    return (
      <CockpitModal
        title="查看图片"

        handleClose={() => this.setState({ isShowBigImgModal: false })}
      >
        <img style={{ width: '100%' }} src={this.state.bigImgSrc} />
      </CockpitModal>
    )
  }

  // 园区无废贡献
  getYuanQuDevote = () => {
    const { isShowDevote } = this.state;
    if(!isShowDevote) return;
    return (
      <Animation className="zoomIn">
        <div className={styles["yuan-qu-devote"]}>
          诸暨市绿色循环园区自2020年6月工程相继投运以来，
          平均每日可处置园区外生活垃圾605t，污水200t，报废汽车/电器等125t，园林废物63t，餐厨垃圾205t，建筑垃圾125t。
          园区内协同利用沼气23t，回用水56t，渗沥液54t，干化污泥52t，蒸汽112t，肥料13t。协同利用率高达93.4%。
          为实现园区内“大无废”做出巨大贡献。
        </div>
      </Animation>
    )
  }

  // 细胞无废贡献
  getXiBaoDevote = () => {
    const { isShowXiBaoDevote } = this.state;
    if(!isShowXiBaoDevote) return;
    return (
      <Animation className="zoomIn">
        <div className={styles["yuan-qu-devote"]}>
          自2020年4月投运以来，嵊州市垃圾焚烧厂平均每日处理生活垃圾795吨，较少二氧化碳排放15.3万吨，节约标煤8.5万吨
        </div>
      </Animation>
    )
  }

  // 细胞模范无废贡献
  getXiBaoMoFanDevote = () => {
    const { isShowXibaoMoFanDevote } = this.state;
    if(!isShowXibaoMoFanDevote) return;
    return (
      <Animation className="zoomIn">
        <div className={styles["yuan-qu-devote"]}>
          2017年承担市级科技计划项目“农业废弃物制作茶园有机肥技术与设备开发研究项目”。
          该科研项目充分利用企业现有农业设施条件的基础，在专业科研院所及台湾专家的技术指导下，就地就近取材，通过本单位周边农业废弃物的回收，
          如茶叶渣、茶棒、茶梗、植物纤维性、畜禽粪便废弃物等，并通过农业废弃物资源综合利用技术研究，
          包括茶园废弃物、笋壳、猪羊牛粪便等快速分级发酵制肥技术和耐高温微生物菌种的筛选、配比优化技术。
          项目实施二年内，自制生物有机肥6843.43吨，自用生物有机肥2193.43吨，提供推广合作单位5168吨，创收1081.26万元，利润726.77万元。
          推广合作单位分布在浙江绍兴、浙江杭州等地，推广有机肥施用茶园20374亩。
        </div>
      </Animation>
    )
  }

  // 设置地图中心点和缩放比例
  setZoomAndCenter = () => {
    this.map && this.map.setZoomAndCenter(10, [120.633541, 29.803041]);
  }

  // 园区详情地图遮罩图例
  getYuanQuChart = () => {
    const { isShowDevote } = this.state;

    return (
      <div
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          height: '100vh',
          width: '100vw',
          visibility: isShowDevote ? "visible" : 'hidden',
          zIndex: isShowDevote ? "" : '-1',
        }}
      >

      </div>
    )
  }

  render() {
    let t = this;
    let { typeBtnKey } = t.state;
    return (
      <div className={styles['process-supervision']}>
        <CockpitContainer
          title='生产运行集成监管平台'
          handleDropClick={t.handleSwitchChange.bind(t, "default")}
        >
          {t.getMap()}
          {/* { t.getTypeButton() } */}
          {/* {t.getMenuButton()} */}
          {t.getLeftSlider()}
          {t.getrightSlider()}
          {/* {this.getHeatMapAbout()} */}
          {/* <LeftContent type={typeBtnKey}/>
          <RightContent type={typeBtnKey}/> */}
          {this.getBigImgModal()}
          {this.getYuanQuDevote()}
          {/* {this.getYuanQuChart()} */}
          {this.getXiBaoDevote()}
          {this.getXiBaoMoFanDevote()}
        </CockpitContainer>
      </div>
    )
  }
}

export default ProcessSupervision;
